package com.me {
	import com.me.components.map.MapScene;

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	import mx.controls.Alert;

	/**
	 *
	 * @author yw
	 *
	 * @Date 2011-9-16 下午03:11:56
	 */
	public class FileLoader {
		private static var _instance:FileLoader;

		private var loaderDic:Dictionary = new Dictionary();

		private var loadedResource:Dictionary = new Dictionary();

		private var loadedCallback:Dictionary = new Dictionary();

		public function FileLoader(enforce:SingletonEnfroce) {
			if (enforce == null) {
				throw new Error("FileLoader can not be instance");
			}
		}

		public static function getInstance():FileLoader {
			if (_instance == null) {
				_instance = new FileLoader(new SingletonEnfroce());
			}
			return _instance;
		}

		public function loadFile(file:File, loaded:Function):void {
			if (loaded == null || file == null || !file.exists) {
				return;
			}

			if (loadedResource[file.url]) {
				loaded.call(null, loadedResource[file.url]);
				return;
			}

			loadedCallback[file.url] = loaded;

			var loader:Loader = new Loader();
			loaderDic[file.url] = loader;
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			loader.load(new URLRequest(file.nativePath));
		}

		private function ioErrorHandler(e:IOErrorEvent):void {
			Alert(e.text);
		}

		private function loadComplete(e:Event):void {
			var url:String = e.currentTarget.url;
//			var loaded:Bitmap = e.currentTarget.content as Bitmap;
//			var bitD:BitmapData = new BitmapData(loaded.bitmapData.width, loaded.bitmapData.height);
			loadedResource[url] = e.target.content;
			(loadedCallback[url] as Function).call(null, loadedResource[url]);
			loadedCallback[url] = null;
			loaderDic[url] = null;
			e.currentTarget.removeEventListener(Event.COMPLETE, loadComplete);
//			e.currentTarget.loader.unload();
		}

//		public function release(file:File):void {
//			if (loaderDic[file.url]) {
//				loaderDic[file.url].unload();
//				loaderDic[file.url] = null;
//				loadedCallback[file.url] = null;
//			}
//		}
	}
}

class SingletonEnfroce {

}